static 您所在的位置:网站首页 JavaScript 中的静态变量 D栈 static

static

2024-05-20 04:30| 来源: 网络整理| 查看: 265

本页介绍类的公有静态属性,包括静态方法、静态访问器和静态字段。

关于私有静态特性,请参阅私有属性。 关于实例特性,请参阅方法定义、getter、setter 和公有类字段。

公有静态特性是使用 static 关键字声明的。在类求值时,使用 [[DefineOwnProperty]] 语义(本质上是 Object.defineProperty())将它们添加到类构造函数中。类构造函数会再次访问它们。

静态方法通常是实用函数,例如创建或克隆实例的函数。当你希望一个字段在每个类中只存在一次,而不是在你创建的每个类实例中都存在时,公有静态字段就很有用。这对缓存、固定配置或其他不需要在实例间复制的数据非常有用。

静态字段名称可以计算。计算表达式中的 this 值是类定义周围的 this,而引用类的名称则会导致 ReferenceError,因为类尚未初始化。在此表达式中,await 和 yield 按预期工作。

静态字段可以有初始化器。没有初始化器的静态字段将被初始化为 undefined。公有静态字段不会在子类中重新初始化,但可以通过原型链访问。

jsclass ClassWithStaticField { static staticField; static staticFieldWithInitializer = "静态字段"; } class SubclassWithStaticField extends ClassWithStaticField { static subStaticField = "子类的字段"; } console.log(Object.hasOwn(ClassWithStaticField, "staticField")); // true console.log(ClassWithStaticField.staticField); // undefined console.log(ClassWithStaticField.staticFieldWithInitializer); // "静态字段" console.log(SubclassWithStaticField.staticFieldWithInitializer); // "静态字段" console.log(SubclassWithStaticField.subStaticField); // "子类的字段"

在字段初始化器中,this 指向当前类(也可通过其名称访问),super 指向基类构造函数。

jsclass ClassWithStaticField { static baseStaticField = "基类静态字段"; static anotherBaseStaticField = this.baseStaticField; static baseStaticMethod() { return "基类静态方法输出"; } } class SubClassWithStaticField extends ClassWithStaticField { static subStaticField = super.baseStaticMethod(); } console.log(ClassWithStaticField.anotherBaseStaticField); // "基类静态字段" console.log(SubClassWithStaticField.subStaticField); // "基类静态方法输出"

表达式是同步求值的。不能在初始化表达式中使用 await 或 yield}。(将初始化表达式视为隐式封装在函数中。)

静态字段初始化器和静态初始化块是逐个求值的。字段初始化器可以引用其上的字段值,但不能引用其下的字段值。所有静态方法都会事先添加并可被访问,但如果它们引用的字段在被初始化的字段的下方,则调用它们时可能会出现与预期不符的情况。

备注: 对于私有静态字段而言,这一点更为重要,因为访问未初始化的私有字段会抛出 TypeError,即使该私有字段已在下面声明。(如果未声明私有字段,则会提前抛出 SyntaxError。)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有